#ifndef UTI_MEMMAN_H_
#define UTI_MEMMAN_H_
#pragma once
#include "sys_config.h"
#include "uti_bar.h"
using namespace std;

template <class T>
class MemMan
{
public:
	MemMan(unsigned int unicnt, void (*pfunc)()):m_unicnt(unicnt), m_pfunc(pfunc)
	{ 

		m_unitindex = 0;
		m_pmem = new T[m_unicnt];



		if (NULL == m_pmem)
		{
			cerr<<"[MemMan] Not enough memory "<<endl;
			return;
		}

		//printf("total size is:%d\n", sizeof(m_pmem));

		//printf("unit size is:%d\n", sizeof(T));

		memset(m_pmem, 0, sizeof(T) * m_unicnt);
	}

	~MemMan()
	{
		if (NULL != m_pmem)
		{
			delete []m_pmem;
			m_pmem = NULL;
		}

	}

	void NextUnitPointer(T** ppOutmem, unsigned int* pOutindex);

	void InitUnitPointer(T** ppOutmem, unsigned int* pOutindex);

private:	
	unsigned int m_unicnt;
	void (*m_pfunc)();

	T* m_pmem;
	unsigned int m_unitindex;

};




template <class T>
void MemMan<T>::InitUnitPointer(T** ppOutmem, unsigned int* pOutindex)
{
	*ppOutmem = m_pmem;
	*pOutindex = m_unitindex;

}

template <class T>
void MemMan<T>::NextUnitPointer(T** ppOutmem, unsigned int* pOutindex)
{
	m_unitindex++;

	if (m_unitindex >= m_unicnt)
	{
		//call register function
		if (NULL != m_pfunc)
		{
			m_pfunc();
		}
		memset(m_pmem, 0, sizeof(T) * m_unicnt);

		m_unitindex = 0;
	}

	*ppOutmem = m_pmem + m_unitindex;
	*pOutindex = m_unitindex;
}





#endif